/**
 *
 * User: c3t
 * Date: 13-12-12
 * Time: 下午12:45
 */
define(['lib/XmlHttpRequest','lib/getNodesByPath'], function (xhr,obj) {
        var areadoc = null;
        window.onload = init;
        function init() {
            initDoc();
            var province = document.getElementById("province");
            province.onchange=function() {
                setAddress(areadoc,"city","//province[@value="+this.value+"]/city");
            }
            var city = document.getElementById("city");
            city.onchange=function() {
                setAddress(areadoc,"country","//city[@value="+this.value+"]/country");

            }
        }

        function setAddress(root,nodeName,path) {
            var ns=obj.getNodesByPath(root,path);
            insertOption(ns,nodeName);
        }

        function insertOption(nodes,nodeName) {
            //得到要插入节点的select元素
            var selectNode = document.getElementById(nodeName);
            //设置select默认显示第一个option
            selectNode.options.length=1;
            //遍历所传的节点集合得到value，组装成option插入select里面
            for(var i =0;i<nodes.length;i++) {
                var optionNode = document.createElement("option");
                optionNode.text=nodes[i].getAttribute("name");
                optionNode.value=nodes[i].getAttribute("value");
                selectNode.add(optionNode);
            }
        }

        function initDoc() {
            xhr.open("GET","../Area.xml",true);
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4 && xhr.status==200) {
                    areadoc = xhr.responseXML;
                    var path = "/address/province";
                    setAddress(areadoc,"province",path);
                }
            }
            xhr.send();
        }
    }
);
